import React, { forwardRef, PureComponent } from 'react'
import { DatePicker, Form, message, Radio, TimePicker } from 'antd'
import moment from 'moment'
import { connect } from '@umijs/max'
import { getScheduleDetail, saveSchedule } from '../../../api'
import styles from './index.less'

const { Item, List } = Form
const { RangePicker } = DatePicker

class DispatchConf extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      spreadSta: false,
      taskNode: {},
    }
    this.configurationForm = React.createRef()
  }

  componentDidMount() {
    this.setState(
      {
        taskNode: this.props?.taskNode,
      },
      () => {
        const { taskNode } = this.state
        const { nodeId } = taskNode || {}
        this.getDetail(nodeId)
      },
    )
  }

  UNSAFE_componentWillUpdate(nextProps) {
    if (nextProps.taskNode != this.props.taskNode) {
      // eslint-disable-next-line react/no-will-update-set-state
      this.setState(
        {
          taskNode: nextProps.taskNode,
        },
        () => {
          const { taskNode } = this.state
          const { nodeId } = taskNode || {}
          this.getDetail(nodeId)
        },
      )
    }
  }

  getDetail = (nodeId) => {
    const params = {
      nodeId,
    }
    getScheduleDetail(params).then((res) => {
      if (res.status === 200 && res.data) {
        const rangeList = []
        const startTime = `${res.data.startTimeHour}:${res.data.startTimeMin}`
        const entTime = `${res.data.endTimeHour}:${res.data.endTimeMin}`
        res.data.rangeList.map((item) => {
          rangeList.push({
            effectiveDate: [moment(item.effectiveDateStart, 'YYYY-MM-DD'), moment(item.effectiveDateEnd, 'YYYY-MM-DD')],
          })
        })
        this.configurationForm?.current?.setFieldsValue({
          effectDayType: res.data.effectDayType || 0,
          time: [moment(startTime, 'HH:mm'), moment(entTime, 'HH:mm')],
          rangeList,
        })
      }
    })
  }

  saveSchedule = (allValues) => {
    const { taskNode } = this.state
    const { nodeId } = taskNode || {}
    const startTime = allValues.time && allValues.time[0]?.format('HH:mm')?.split(':') || null
    const endTime = allValues.time && allValues.time[1]?.format('HH:mm')?.split(':') || null
    const rangeList = []
    allValues.rangeList && allValues.rangeList.map((item) => {
      const effectiveDateStart = item && item.effectiveDate && item.effectiveDate[0] && item.effectiveDate[0]?.format('YYYY-MM-DD') || null
      const effectiveDateEnd = item && item.effectiveDate && item.effectiveDate[1] && item.effectiveDate[1]?.format('YYYY-MM-DD') || null
      if (effectiveDateStart && effectiveDateEnd) {
        rangeList.push({
          effectiveDateEnd,
          effectiveDateStart,
        })
      }
    })
    saveSchedule({
      nodeId,
      effectDayType: allValues.effectDayType,
      startTimeHour: startTime && startTime[0] || null,
      startTimeMin: startTime && startTime[1] || null,
      endTimeHour: endTime && endTime[0] || null,
      endTimeMin: endTime && endTime[1] || null,
      rangeList,
    }).then((res) => {
      if (res.status === 200) {
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
    })
  }

  // eslint-disable-next-line react/no-unused-class-component-methods
  toggleDispatchConf = (spreadStaParams = undefined, isClear = false) => {
    if (this.state.spreadSta) {
      isClear && this.configurationForm?.current?.resetFields()
    }
    this.setState((prevState) => ({
      spreadSta: spreadStaParams !== undefined ? spreadStaParams : !prevState.spreadSta,
    }))
  };

  valuesChange = (value, allValues) => {
    const key = Object.keys(value)[0]
    this.saveSchedule(allValues)
  }

  render() {
    const {
      spreadSta,
    } = this.state
    return (
      <div className={`${styles.node_detail} ${spreadSta ? styles.spread : ''}`}>
        <div className={styles.node_detail_column}>调度配置</div>
        <Form
          className={styles.form}
          colon={false}
          layout="vertical"
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
          onValuesChange={this.valuesChange}
          ref={this.configurationForm}
        >
          <Item
            required
            label="生效区间"
            name="effectDayType"
            rules={[{ required: true, message: '请选择生效区间' }]}
          >
            <Radio.Group
              placeholder="请选择函数类型"
            >
              <Radio value={0}>每天</Radio>
              <Radio value={1}>周一至周五</Radio>
            </Radio.Group>
          </Item>
          <Item
            required
            label="日期范围"
            rules={[{ required: true, message: '请选择日期范围' }]}
          >
            <List
              name="rangeList"
              initialValue={[{
                effectiveDate: undefined,
              }]}
            >
              {(fields, { add, remove }) => fields.map(({ key, name, ...restField }, index) => (
                <Item
                  key={key}
                >
                  <div className={styles.parameter_item}>
                    <Item
                      name={[name, 'effectiveDate']}
                      noStyle
                      style={{ display: 'inline-block', width: 'calc(50% - 8px)' }}
                      rules={[
                        { required: true, message: '请选择日期范围' },
                      ]}
                    >
                      <RangePicker
                        style={{ width: 'calc(100% - .25rem)' }}
                        showTime
                        format="YYYY-MM-DD"
                        allowClear
                        placeholder={['开始时间', '结束时间']}
                      />
                    </Item>
                    <div className={styles.item_btn_wrap}>
                      {
                        fields.length - 1 === index && <i className={`iconfont icon-tianjia1 ${styles.add_sign}`} onClick={() => add()} />
                      }
                      {
                        fields.length - 1 !== 0 && <i className={`iconfont icon-shanchu ${styles.del_sign}`} onClick={() => remove(name)} />
                      }
                    </div>
                  </div>
                </Item>
              ))}
            </List>
          </Item>
          <Item required name="time" label="时间范围" rules={[{ required: true, message: '请选择时间范围' }]}>
            <TimePicker.RangePicker format="HH:mm" />
          </Item>
        </Form>
      </div>
    )
  }
}

class WrappedComponentRef extends PureComponent {
  render() {
    const { forwardedRef, ...rest } = this.props
    return (
      <DispatchConf ref={forwardedRef} {...rest} />
    )
  }
}

const IComponent = connect(({ realTimeScriptDev }) => ({ ...realTimeScriptDev }))(WrappedComponentRef)

export default forwardRef((props, ref) => <IComponent {...props} forwardedRef={ref} />)
